<script setup lang="tsx">
import { computed, ref } from 'vue';
import { ElButton, ElPopconfirm, ElTag } from 'element-plus';
import { CopyDocument } from '@element-plus/icons-vue';
import {
  fetchDeleteDictBatchByIds,
  fetchDeleteDictById,
  fetchGetDictByPage,
  fetchGetDictTextByIds
} from '@/service/api';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import DictFormDrawer from '@/views/system/dict/modules/dict-form-drawer.vue';
import DictSearch from '@/views/system/dict/modules/dict-search.vue';

defineOptions({ name: 'DictManage' });

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetDictByPage,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    condition: {}
  },
  columns: () => [
    { type: 'selection', width: 48 },
    { prop: 'index', label: $t('common.index'), width: 64 },
    {
      prop: 'code',
      label: '字典编码',
      minWidth: 200,
      align: 'left',
      formatter: row => (
        <div class="flex justify-between flex-items-center">
          <text class="flex-1 overflow-hidden text-ellipsis">{row.code}</text>
          <el-icon>
            <CopyDocument class="btn-clipboard cursor-pointer" data-clipboard-text={row.code} />
          </el-icon>
        </div>
      )
    },
    { prop: 'name', label: '字典标签', minWidth: 200, align: 'left' },
    { prop: 'remark', label: '备注', minWidth: 200, align: 'left' },
    {
      prop: 'enabled',
      label: $t('form.enabled'),
      width: 120,
      align: 'center',
      formatter: row => (
        <ElTag type={row.enabled === 1 ? 'success' : 'danger'}>
          {row.enabled === 1 ? $t('form.enabledOptions.enabled') : $t('form.enabledOptions.disabled')}
        </ElTag>
      )
    },
    { prop: 'orderNum', label: $t('form.orderNum'), width: 120, align: 'center' },
    { prop: 'createTime', label: $t('common.createTime'), width: 200, align: 'left' },
    {
      prop: 'operate',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      formatter: row => (
        <div class="flex-center">
          <ElButton type="primary" plain size="small" onClick={() => gotoSub(row)}>
            子级
          </ElButton>
          <ElButton type="primary" plain size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(row.id)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer,
} = useTableOperate(data, getData);

async function handleDelete(id: CommonType.IdType) {
  try {
    // request
    const { error } = await fetchDeleteDictById(id);
    // success
    if (error) return;
    await onDeleted();
  } catch {
    //
  }
}

async function handleBatchDelete() {
  // ids
  const ids: Array<CommonType.IdType> = checkedRowKeys.value.map(item => item.id);
  // request
  const { error } = await fetchDeleteDictBatchByIds(ids);
  if (error) return;
  await onBatchDeleted();
}

/** 编辑租户信息 */
function edit(id: CommonType.IdType) {
  handleEdit(id);
}

/** 当页最大的 orderNum */
const maxOrderNum = computed(() => {
  if (data.value && data.value.length > 0) {
    return data.value[data.value.length - 1].orderNum;
  }
  return 0;
});

const parentIdStack = ref<CommonType.IdType[]>([]);

const parentDictText = ref<string>();

// 获取权限层级描述文本
async function handleGetDictTextByIds() {
  const { data: text, error } = await fetchGetDictTextByIds(parentIdStack.value);
  if (error) return;
  parentDictText.value = text;
}

// 查入子级权限列表
async function gotoSub(row: Api.System.Dict.DictRecord) {
  parentIdStack.value.push(row.id);
  const cond = searchParams.condition || {};
  cond.parentId = row.id;
  searchParams.condition = cond;
  await getDataByPage();
  await handleGetDictTextByIds();
}

async function handleBackUp() {
  if (parentIdStack.value && parentIdStack.value.length > 0) {
    parentIdStack.value.pop();
  }
  const cond = searchParams.condition || {};
  if (parentIdStack.value && parentIdStack.value.length > 0) {
    cond.parentId = parentIdStack.value[parentIdStack.value.length - 1];
  } else {
    // null/0-最顶层列表，后台会自动将null转为0，因为顶层数据的 parentId 为 0
    cond.parentId = 0;
  }
  searchParams.condition = cond;
  await getDataByPage();
  await handleGetDictTextByIds();
}
</script>

<template>
  <ElContainer>
    <ElHeader>
      <ElCard class="card-wrapper" :body-style="{ paddingTop: 0, paddingBottom: 0 }">
        <DictSearch v-model="searchParams.condition" @reset="resetSearchParams" @search="getDataByPage" />
      </ElCard>
    </ElHeader>
    <ElHeader v-if="!!parentDictText">
      <ElAlert type="info" :closable="false">父项字典：{{ parentDictText }}</ElAlert>
    </ElHeader>
    <ElMain>
      <ElCard class="h-full sm:flex-1-hidden card-wrapper">
        <template #header>
          <div class="flex flex-wrap items-center justify-between gap-5">
            <p>字典列表</p>
            <TableHeaderOperation
              v-model:columns="columnChecks"
              :disabled-delete="checkedRowKeys.length === 0"
              :loading="loading"
              @add="handleAdd"
              @delete="handleBatchDelete"
              @refresh="getData"
            >
              <template #prefix>
                <ElButton
                  v-loading="loading"
                  type="primary"
                  plain
                  :disabled="!searchParams.condition?.parentId"
                  @click="handleBackUp"
                >
                  返回上级
                </ElButton>
              </template>
            </TableHeaderOperation>
          </div>
        </template>
        <div class="h-[calc(100%-45px)]">
          <ElTable
            v-loading="loading"
            height="100%"
            border
            class="sm:h-full"
            :data="data"
            row-key="id"
            show-overflow-tooltip
            @selection-change="checkedRowKeys = $event"
          >
            <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
          </ElTable>
        </div>
        <div class="mt15px flex justify-end">
          <ElPagination
            v-if="mobilePagination.total"
            background
            layout="total,prev,pager,next,sizes"
            v-bind="mobilePagination"
            @current-change="mobilePagination['current-change']"
            @size-change="mobilePagination['size-change']"
          />
        </div>
      </ElCard>
      <DictFormDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :max-order-num="maxOrderNum"
        :parent-id="searchParams.condition?.parentId"
        @submitted="getDataByPage(mobilePagination.currentPage)"
      />
    </ElMain>
  </ElContainer>
</template>

<style scoped>
.el-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .el-header {
    padding: 0;
    height: auto;
  }

  .el-main {
    padding: 0;
    height: 0;
    flex: 1;
  }
}

:deep(.el-card) {
  display: flex;
  flex-direction: column;
}

:deep(.el-card .el-card__body) {
  flex: 1;
  height: 0;
}

:deep(.el-table .cell) {
  padding: 0 10px;
}
</style>
